import { ChatMessage } from '@database/entity/chat'
import { getFormattedCurrentTime } from "@/assets/ts/utils"


export function chatEntityInit (db: IDBDatabase) {
    if (db.objectStoreNames.contains('chat')) {
      return
    }
    const objectStore = db.createObjectStore('chat', {
      keyPath: 'id',
      autoIncrement: true,
    })
    objectStore.createIndex('id', 'id', { unique: true })
    objectStore.createIndex('user', 'user', { unique: false })
    objectStore.createIndex('type', 'type', { unique: false })
    objectStore.createIndex('content', 'content', { unique: false })
  }


  export function list (db: IDBDatabase): Promise<ChatMessage[]> {
    return new Promise((resolve, reject) => {
        const objectStore = db.transaction('chat').objectStore('chat')
        const request = objectStore.openCursor()
        const chatList: ChatMessage[] = []
        request.onsuccess = function (event) {
          if (!event.target) {
            reject(new Error('could not find target'))
            return
          }
          const target = event.target as CustomIDBCursorEventTarget
          const cursor = target.result
          if (cursor) {

            const value = cursor.value as unknown as ChatMessage;
            chatList.push(value)
            cursor.continue()
          } else {
            resolve(chatList)
          }
        }
    
        request.onerror = function () {
          // 数据写入失败
          const error = new Error('数据读取失败')
          // error.__detail = event
          reject(error)
        }
      })

  }

  

  export function add (db: IDBDatabase,chat:ChatMessage) {
    
    if (db.objectStoreNames.contains('data-store')) {
      return
    }

    return new Promise((resolve, reject) => {

      let data = {
        id: getFormattedCurrentTime(),
        user: chat.user,
        type: chat.type,
        content: chat.content
      }

      const request = db.transaction(['chat'], 'readwrite').objectStore('chat').put(data)

      request.onsuccess = function (event) {
        // 数据写入成功
        resolve(event)
      }

      request.onerror = function () {
        // 数据写入失败
        const error = new Error('数据写入失败')
        reject(error)
      }
   })

  }


